package com.augurit.common.common.http.kt.model

import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException

/**
 *  author : yanghaozhang
 *  date : 2022/5/3 22:46
 *  description :
 */
class HttpResultErrorException(val isSuccess: Boolean, val code: Int = -1, msg: String?) : IllegalArgumentException(msg ?: "数据异常")

class ApiException(msg: String?) : Exception(msg) {
    companion object {
        fun handleException(e: Throwable): ApiException {
            val msg = when (e) {
                is UnknownHostException -> {
                    "网络不可用"
                }
                is SocketTimeoutException -> {
                    "请求网络超时"
                }
                is ConnectException -> {
                    "请求连接失败"
                }
                is HttpException -> {
                    convertStatusCode(e)
                }
                is JsonParseException, is ParseException, is JSONException -> {
                    "数据解析错误"
                }
                else -> {
                    e.message ?: "获取数据失败"
                }
            }
            return ApiException(msg)
        }

        private fun convertStatusCode(httpException: HttpException): String {
            return when {
                httpException.code() == 500 -> {
                    "服务器发生错误"
                }
                httpException.code() == 404 -> {
                    "请求地址不存在"
                }
                httpException.code() == 403 -> {
                    "请求被服务器拒绝"
                }
                httpException.code() == 307 -> {
                    "请求被重定向到其他页面"
                }
                else -> {
                    httpException.message()
                }
            }
        }
    }
}